package com.ruoyi.web.cp.service.cp;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.web.cp.domain.rm.CpAo5;
import com.ruoyi.web.cp.service.WinxinService;
import com.ruoyi.web.cp.service.http.CpAo5HttpService;
import com.ruoyi.web.mapper.CpAo5Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author xiesm
 * @Description: TODO
 * @date 2025-08-21 16:56
 */
@Service
public class Ao5Service {
    @Autowired
    private CpAo5Mapper cpAo5Mapper;
    @Autowired
    private CpAo5HttpService cpAo5HttpService;
    @Autowired
    private WinxinService winxinService;
    @Autowired
    private Ao52Service ao52Service;
    @Autowired
    private Ao53Service ao53Service;
    @Autowired
    private Ao5FiveFourStarService ao5FiveFourStarService;

    public void getAo5ListRecent2Day() {
        cpAo5Mapper.deleteDoubleRecode();
        String date = DateUtil.format(new Date(), "yyyy-MM-dd");
        getAo5List(date);
//        getAo5ListFromLeyu();
        CpAo5 cpAo5 = cpAo5Mapper.selectLatest();
        boolean boo = cpAo5Mapper.checkLatestDuplicateInRecent2000();
        if (boo) {
            winxinService.sendTextMessage("1000002", cpAo5.getPreDrawIssue() + " 近2000期相同");
        }
        List<String> frontList = extractFrontOrBackCodes(0, 2, 200, "front");
        List<String> backList = extractFrontOrBackCodes(0, 2, 200, "back");
        String code = cpAo5.getPreDrawCode();
        String frontCode = code.substring(0, code.lastIndexOf(",")).replace(",", "");
        String backCode = code.substring(code.indexOf(",") + 1).replace(",", "");
//        if (frontList != null && frontList.contains(frontCode)) {
//            winxinService.sendTextMessage("1000002", cpAo5.getPreDrawIssue() + " 前4近200期相同");
//
//        }
//        if (backList != null && backList.contains(backCode)) {
//            winxinService.sendTextMessage("1000002", cpAo5.getPreDrawIssue() + " 后4近200期相同");
//        }
        ao52Service.checkAo5_2(null);
        ao53Service.execute("5e5cd336-24e8-41c1-8e59-d0607f951090");
        ao5FiveFourStarService.check2000LastCode();
    }

    public void getAo5List(String date) {
        JSONObject data = cpAo5HttpService.getListFromHwy(date);
        if (CollUtil.isEmpty(data)) {
            return;
        }
        if (!"0".equals(data.getString("errorCode"))) {
            return;
        }
        if (CollUtil.isEmpty(data = data.getJSONObject("result"))) {
            return;
        }
        JSONArray datas = data.getJSONArray("data");
        if (CollUtil.isEmpty(datas)) {
            return;
        }
        List<String> issues = cpAo5Mapper.selectPreDrawIssueByDate(date);
        for (int i = 0; i < datas.size(); i++) {
            JSONObject item = datas.getJSONObject(i);
            String preDrawIssue = item.getString("preDrawIssue");
            String preDrawTime = item.getString("preDrawTime");
            String preDrawCode = item.getString("preDrawCode");
            if (!issues.contains(preDrawIssue)) {
                cpAo5Mapper.insert(new CpAo5(preDrawIssue, preDrawTime, preDrawCode));
            }
        }
    }

    public void getAo5ListFromLeyu() {
        String date = DateUtil.format(DateUtil.beginOfDay(new Date()), "yyyy-MM-dd");
        JSONArray datas = cpAo5HttpService.getListFromOb();
        if (CollUtil.isEmpty(datas)) {
            return;
        }
        List<String> issues = cpAo5Mapper.selectPreDrawIssueByDate(date);
        for (int i = 0; i < datas.size(); i++) {
            JSONObject item = datas.getJSONObject(i);
            String preDrawIssue = item.getString("drawNumber");
            Long preDrawTime = item.getLong("drawTime");
            String preDrawCode = item.getString("result");
            if (!issues.contains(preDrawIssue)) {
                cpAo5Mapper.insert(new CpAo5(preDrawIssue, preDrawTime, preDrawCode));
            }
        }
    }

    public List<String> generateFourDigitNumbers() {
        List<String> numbers = new ArrayList<>(10000);
        for (int i = 0; i <= 9999; i++) {
            numbers.add(String.format("%04d", i));
        }
        return numbers;
    }

    /**
     * 根据type提取codes的前4或后4个元素
     *
     * @param codes 原始代码列表
     * @param type  类型：front-前4个，back-后4个
     * @return 提取的元素列表
     */
    private List<String> extractFrontOrBackCodes(int minute, int offset, int limit, String type) {
        List<String> codes = cpAo5Mapper.selectRecentLimitN(minute, offset, limit);

        if (CollUtil.isEmpty(codes)) {
            return null;
        }
        List<String> result = new ArrayList<>();
        if ("front".equals(type)) {
            // 取前4个元素
            for (int i = 0; i < codes.size(); i++) {
                String code = codes.get(i);
                result.add(code.substring(0, code.lastIndexOf(",")).replace(",", ""));
            }
        } else if ("back".equals(type)) {
            // 取后4个元素
            for (int i = 0; i < codes.size(); i++) {
                String code = codes.get(i);
                result.add(code.substring(code.indexOf(",") + 1).replace(",", ""));
            }
        }
        return result;
    }

    public String getAo5ListOfFrontBack4(int limit, String type) {
        List<String> result = extractFrontOrBackCodes(5, 1, limit, type);
        if (CollUtil.isEmpty(result)) {
            return "";
        }
        // 生成完整的0000-9999列表
        List<String> allNumbers = generateFourDigitNumbers();

        // 从完整列表中移除已选择的元素
        allNumbers.removeAll(result);
        System.out.println(allNumbers.size());
        return CollUtil.join(allNumbers, ";");
    }
}
